#@PydevCodeAnalysisIgnore
# Create your views here.

import os
import datetime
from xml.dom import minidom

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

from settings import DIRS

from analysis.Indicators import compute_indicators
#from analysis.Indicators import save_indicators_to_xml

title = "IASNA core:"
welcome = "Welcome to IASNA System. This module IASNA-core enable you to apply the SNA indicators to a xml file with IASNA format."
menu = {"Analysis": {"status": "inactive", "short_name": "Analysis", "url": "/iasna/analysis"}, 
        "Results": {"status": "inactive", "short_name": "Results", "url": "/iasna/results"},
        #"Upload xml file": {"status": "inactive", "short_name": "upload", "url": "/iasna/upload"}, 
        }

#functions1 = {"": {"status": "active", "short_name": "... to IASNA", "url": "/teamquest/"}}
functions1 = {}
modules = {"Iasna Core": {"status": "active", "short_name": "iasna", "url": "/iasna/"}, 
           "Iasna Teamquest": {"status": "inactive", "short_name": "teamquest", "url": DIRS["TEAMQUEST_URL"]},
           "Iasna Reflexion": {"status": "inactive", "short_name": "reflexion", "url": DIRS["REFLEXION_URL"]},
           "Iasna Recommendation": {"status": "inactive", "short_name": "recommendation", "url": DIRS["RECOMMENDATION_URL"]},
           }

TEMPLATES_MEDIA_URL = DIRS["PROJECT_MEDIA_URL"] + 'myTemplates/snow-flakes/'
CALENDAR_MEDIA_URL = DIRS["PROJECT_MEDIA_URL"] + 'calendar/'

#configurar active en grafico
def link_activated(list_links, key):
    for list_link in list_links:
        if list_link.lower().replace(" ", "_") == key.lower().replace(" ", "_"):
            list_links[list_link]["status"] = "active"
        else: list_links[list_link]["status"] = "inactive"

def list_files_in_path(path, ext):
    files = os.listdir(path)
    for file in files:
        if not file.lower().endswith('.' + ext.lower()):
            files.remove(file)
    return files

def index(request):
    link_activated(menu, "")
    link_activated(functions1, "")
    
    t = loader.get_template('core1.html')
    subtitle = ''
    
    c = Context({
        'title': title,
        'subtitle': subtitle,
        'welcome': welcome,
        'menu': menu,
        'options': menu,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))

def analysis(request):
    functions1 = {}
    fun1 = list_files_in_path(DIRS["CORE_MEDIA_ROOT"], 'xml')
    for f in fun1:
        functions1[f.replace(".xml", "")] = {"status": "inactive", "url": "/iasna/analysis/" + f.replace(".xml", "")}
    
    link_activated(menu, "Analysis")
    link_activated(functions1, "")
    
    t = loader.get_template('core1.html')
    subtitle = 'Analysis'
    
    c = Context({
        'title': title,
        'subtitle': subtitle,
        'welcome': welcome + '\n\nIt applies over an IASNA xml file the collaborative indicators.',
        'menu': menu,
        'functions': functions1,
        'options': functions1,
        #'fileupload': fileupload,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
        'CALENDAR_MEDIA_URL': CALENDAR_MEDIA_URL,
    })
    return HttpResponse(t.render(c))

def read_dates_from_to(xmlfile):
    datetime_start = {}
    datetime_end = {}
    
    #try:
    if os.path.isfile(DIRS["CORE_MEDIA_ROOT"] + xmlfile + '.xml'):
        try: level1 = minidom.parse(DIRS["CORE_MEDIA_ROOT"] + xmlfile + '.xml')
        except: return {}
        
        for level2 in level1.getElementsByTagName("situation"):
            for level3 in level2.getElementsByTagName("activity"):
                for level4 in level3.getElementsByTagName("actions"):
                    for level5 in level4.getElementsByTagName("action"):
                        if "date" not in datetime_start:
                            datetime_start["date"] = str(level5.getAttribute("datetime")).split()[0]
                            datetime_start["time"] = str(level5.getAttribute("datetime")).split()[1]
                        datetime_end["date"] = str(level5.getAttribute("datetime")).split()[0]
                        datetime_end["time"] = str(level5.getAttribute("datetime")).split()[1]
        aux = datetime_start["date"] = datetime_start["date"].split('/')
        datetime_start["date"] = aux[2] + aux[0] + aux[1]
        aux = datetime_end["date"] = datetime_end["date"].split('/')
        datetime_end["date"] = aux[2] + aux[0] + aux[1]
    #except: return {}
    
    return {"datetime_start": datetime_start, "datetime_end": datetime_end}

def analysis_group(request, xmlfile):
    functions1 = {}
    fun1 = list_files_in_path(DIRS["CORE_MEDIA_ROOT"], 'xml')
    for f in fun1:
        functions1[f.replace(".xml", "")] = {"status": "inactive", "url": "/iasna/analysis/" + f.replace(".xml", "")}
    
    link_activated(menu, "Analysis")
    link_activated(functions1, xmlfile)
    
    t = loader.get_template('core1.html')
    subtitle = 'Analysis for activity ' + xmlfile
    
    dates = read_dates_from_to(xmlfile)
    
    #formulario
    myform = AnalysisForm()
    
    c = Context({
        'title': title,
        'subtitle': subtitle,
        'welcome': welcome + '\n\r\n\rIt applies over an IASNA xml file the collaborative indicators.',
        'menu': menu,
        'functions': functions1,
        'xmlfile': xmlfile,
        'analysisform': myform,
        'dates': dates,
        #'options': functions1,
        #'fileupload': fileupload,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
        'CALENDAR_MEDIA_URL': CALENDAR_MEDIA_URL,
    })
    return HttpResponse(t.render(c))

def results(request):
    functions1 = {}
    fun1 = list_files_in_path(DIRS["CORE_RESULTS_ROOT"], 'xml')
    for f in fun1:
        functions1[f.replace(".xml", "")] = {"status": "inactive", "url": "/iasna/results/" + f.replace(".xml", "")}
    
    link_activated(menu, "Results")
    link_activated(functions1, "")
    
    t = loader.get_template('core1.html')
    subtitle = 'Results'
    
    c = Context({
        'title': title,
        'subtitle': subtitle,
        'welcome': welcome + '\n\nIt displays the results after apply over an IASNA xml file the collaborative indicators.',
        'menu': menu,
        'functions': functions1,
        'options': functions1,
        
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))

def results_group(request, xmlfile):
    link_activated(menu, "Results")
    
    
    t = loader.get_template('core1.html')
    subtitle = 'Analysis applied! ' + xmlfile
    link_to_visit = {"Reflexion Board " + xmlfile: {"url": DIRS["REFLEXION_URL"] + "anytype/" + xmlfile }, }
    indicators = None
    
    if request.method == 'POST':
        data = request.POST
        if "criterion" in data:
            if data['criterion'] == 'AD':
                if 'minute_segmentation_chk' in data and data['minute_segmentation_chk'] == 'on':
                    try: indicators = compute_indicators(xmlfile, datetime.datetime.strptime(data['datetime_start'], '%Y-%m-%d %H:%M'), datetime.datetime.strptime(data['datetime_end'], '%Y-%m-%d %H:%M'), int(data['minute_segmentation']))
                    except Exception as ex: subtitle = "Unknown Error, please review your option configuration for an optimal results."
                else: 
                    try: indicators = compute_indicators(xmlfile, datetime.datetime.strptime(data['datetime_start'], '%Y-%m-%d %H:%M'), datetime.datetime.strptime(data['datetime_end'], '%Y-%m-%d %H:%M'), 0)
                    except Exception as ex: subtitle = "Unknown Error, please review your option configuration for an optimal results."
            else: 
                try: indicators = compute_indicators(xmlfile, None, None, 0)
                except Exception as ex: subtitle = "Unknown Error, please review your option configuration for an optimal results."
            
            if indicators is not None and indicators != []: 
                None
                #save_indicators_to_xml(indicators, xmlfile)
                #link_to_visit = {"Reflexion Board " + xmlfile: {"url": DIRS["REFLEXION_URL"] + "anytype/" + xmlfile}, }
            else: 
                subtitle = "No data retrieved from analysis, please review your option configuration for an optimal results."
                link_to_visit = {"Return to analysis " + xmlfile: {"url": DIRS["CORE_URL"] + "analysis/" + xmlfile}, }
        else:
            subtitle = "No data retrieved from analysis, please review your option configuration for an optimal results."
            link_to_visit = {"Return to analysis " + xmlfile: {"url": DIRS["CORE_URL"] + "analysis/" + xmlfile}, }
    
    
    functions1 = {}
    fun1 = list_files_in_path(DIRS["CORE_RESULTS_ROOT"], 'xml')
    for f in fun1:
        functions1[f.replace(".xml", "")] = {"status": "inactive", "url": "/iasna/results/" + f.replace(".xml", "") + '/'}
    link_activated(functions1, xmlfile)
    
    
    
    #mostrar datos
    
    c = Context({
        'title': title,
        'subtitle': subtitle,
        'welcome': welcome + '\n\r\n\rIt displays the analysis obtained applying collaborative indicators. For details visit Reflexion Board to next.',
        'menu': menu,
        'functions': functions1,
        'xmlfile': xmlfile,
        'options': link_to_visit,
        'request_POST': request.POST,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))


#  analysis form

class AnalysisForm(forms.Form):
    criterion = forms.ChoiceField (
        widget=forms.RadioSelect(), 
        choices = (('AS','Analysis for sessions'), ('AD','Analysis for date range'), ),
        label="Criterion")
    #datetime_start = forms.CharField()
    #datetime_end = forms.CharField()
    minute_segmentation_chk = forms.BooleanField(required=False)
    minute_segmentation = forms.IntegerField()
    
    #subject = forms.CharField(max_length=100)
    #message = forms.CharField()
    #sender = forms.EmailField()
    


# uploading xml files

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField()

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            myfile = request.FILES['file']
            handle_uploaded_file(myfile)
            #data = LoadLogToActivity.loadLogToActivity(myfile.name.replace(".xml", ""))
            #LoadLogToActivity.saveLogToActivity(myfile.name.replace(".xml", ""), data)
            return #analysis_results(request)
    else:
        form = UploadFileForm()
    return render_to_response('core1.html', {
                'fileupload': form, 
                "welcome": welcome, 
                'subtitle': 'Error uploading the file',
                'modules': modules,
                'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
                })
    

def handle_uploaded_file(f):
    try:
        destination = open(DIRS["TEAMQUEST_MEDIA_ROOT"] + f.name, 'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
    except IOError: print 'Error writing the file ' + f.name

